
const ologin = document.querySelector(".login")
const owelcome = document.querySelector(".welcome")
const oun = document.querySelector(".un")
const oexit = document.querySelector(".exit")
const ogoCart = document.querySelector(".goCart")

// 读取登录信息
if(localStorage.getItem("isLogin") === "ok"){
    ologin.style.display = "none";
    owelcome.style.display = "block";
    oun.innerHTML = localStorage.getItem("username");
}else{
    ologin.style.display = "block";
    owelcome.style.display = "none";
    oun.innerHTML = "xxx";
}

oexit.onclick = function(){
    localStorage.removeItem("username");
    localStorage.setItem("isLogin", "");
    ologin.style.display = "block";
    owelcome.style.display = "none";
    oun.innerHTML = "xxx";
}

ogoCart.onclick = function(){
    if(localStorage.getItem("isLogin") === "ok"){
        location.href = "./cart.html"
    }else{
        alert("未登录状态，不允许打开购物车，请先登录")
        location.href = "./login.html"
    }
}

// ===============

const oGoodsList = document.querySelector(".goodsList")



ajax("http://localhost:3000/api",res=>{
    res = JSON.parse(res).msg;
    console.log(res);

    let str = "";
    res.forEach(val=>{
        str += `<div class="box" index="${val.proId}">
                    <a href="./detail.html?id=${val.proId}">
                        <img src="${val.img}" alt="">
                        <p>${val.proName}</p>
                        <span>${val.price}</span>
                    </a>
                    <input type="button" class="add" value="加入购物车">
                </div>`
    })
    oGoodsList.innerHTML = str;

},{
    type:"getGoods"
})







function ajax(url, callback, data){
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;
    const xhr = new XMLHttpRequest();
    xhr.open("get",url)
    xhr.onload = function(){
        if(xhr.status === 200){
            callback(xhr.responseText)
        }
    }
    xhr.send();
}


